import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as ContactAction from '../actions/contact'

 import WeaFormmodeTop from './WeaFormmodeTop'
import { WeaTable } from 'comsRedux'

const WeaTableAction = WeaTable.action;
import CustomerContractModal from './contact/customerContractModal'
import {
    WeaTab,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaSelect ,
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
const { getComponent } = WeaTools;

import {Button,Form,Modal,message} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class Contact extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
        }
    }
    componentDidMount() {
    	 const {actions} = this.props;
         actions.setNowRouterCmpath('contact');
         actions.initConditions();
         actions.getRemindCount();
        actions.doSearch();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld!==keyNew) {
            const {actions,isClearNowPageStatus} = this.props;
            actions.unmountClear(isClearNowPageStatus);
            actions.isClearNowPageStatus(false);

            actions.setNowRouterCmpath('contact');
            actions.initConditions();
            actions.getRemindCount();
            actions.doSearch();
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
         return !is(this.props.title,nextProps.title)||
            !is(this.props.dataKey,nextProps.dataKey)||
            !is(this.props.loading,nextProps.loading)||
            !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
            !is(this.props.showSearchAd,nextProps.showSearchAd)||
            !is(this.props.orderFields,nextProps.orderFields)||
            !is(this.props.detailTabKey,nextProps.detailTabKey)||
            !is(this.props.remindCount,nextProps.remindCount)||
            !is(this.props.showSearchAd,nextProps.showSearchAd)||
            !is(this.props.conditioninfo,nextProps.conditioninfo)||
            !is(this.props.searchParamsAd,nextProps.searchParamsAd)||
            !is(this.props.isClearNowPageStatus,nextProps.isClearNowPageStatus)||
            !is(this.props.customerId,nextProps.customerId)||
            !is(this.props.remindInfo,nextProps.remindInfo);
    }
    componentWillUnmount(){
    	const {actions,isClearNowPageStatus} = this.props;
        actions.unmountClear(isClearNowPageStatus);
        actions.isClearNowPageStatus(false);
    }
    render() {
        const {loading,actions,dataKey,title,comsWeaTable,remindCount,detailTabKey,showSearchAd,searchParamsAd,customerId,remindInfo} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const tabDatas = [{key:"info",title:"联系情况"},{key:"plan",title:"联系计划"},{key:"remind",title:`${"联系提醒("+remindCount+")"}`}];
        return (
            <div className="crm-top-req">
                <WeaPopoverHrm />
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                     <WeaFormmodeTop
                        title={title}
                        loading={loading || loadingTable}
                        icon={<i className='icon-coms-crm' />}
                        tabDatas={tabDatas}
                        selectedKey={detailTabKey}
                        onChange={this.changeData.bind(this)}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={false}
                        dropMenuDatas={this.getRightMenu()}

                        buttonsAd={this.getTabButtonsAd()}  //高级搜索底部button
                        searchType={detailTabKey!= "remind" && ['base','advanced']}
                        searchsBaseValue={searchParamsAd.get('description')}  //外部inpt默认初始值
                        setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                        hideSearchAd={()=> actions.setShowSearchAd(false)}
                        searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                        showSearchAd={showSearchAd}
                        onSearch={v=>{actions.doSearch()}}
                        onSearchChange={v=>{actions.saveOrderFields({description:{name:'description',value:v}})}}
                    >
                        <WeaTable 
                            sessionkey={dataKey}
                            hasOrder={true}
                            needScroll={true}
                            onOperatesClick={this.onOperatesClick.bind(this)}
                    	/>
                    </WeaFormmodeTop>
                </WeaRightMenu>
               { detailTabKey== "remind" && <CustomerContractModal ref="customerContractModal" actions={actions} customerId={customerId} remindInfo={remindInfo}/>}
            </div>
        )
    }
    onRightMenuClick(key){
    	 const {actions,comsWeaTable,dataKey} = this.props;
    	if(key == '0'){
            actions.doSearch();
    	}
    	if(key == '1'){
    		actions.setColSetVisible(dataKey,true);
    		actions.tableColSet(dataKey,true)
    	}
    }
    getRightMenu(){
        const {detailTabKey} = this.props;      
        let btns = [];  
       { detailTabKey != "remind" && btns.push({
    		icon: <i className='icon-coms-search '/>,
            content:'搜索',
            key:0
        });}
        btns.push({
    		icon: <i className='icon-coms-Custom '/>,
            content:'显示定制列',
            key:1
    	}); 
    	btns.push({
    		icon: <i className='icon-coms-Collection '/>,
            content:'收藏',
            key:2
    	});
        btns.push({
            icon: <i className='icon-coms-help '/>,
            content:'帮助',
            key:3
        })
    	return btns
    }
     getButtons() {
         const {actions,detailTabKey,dataKey, comsWeaTable,} = this.props;
         const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
        let btnArr = [];
        {detailTabKey != "remind" &&  btnArr.push(<Button type="primary" 
            disabled={!(selectedRowKeys && `${selectedRowKeys.toJS()}`)}
            onClick={()=>{actions.finishWorkPlan({planIds:`${selectedRowKeys.toJS()}`})}}>完成</Button>);}
        return btnArr
    }
     changeData(key){
         const {actions} = this.props;
         actions.setTabKey(key);
        if(key == "remind"){
            actions.getRemindList();
        }else{
            actions.doSearch({selectType:key});
        }
    }
    getTabButtonsAd() {
    	const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    getSearchs() {
    	const { conditioninfo,actions } = this.props;
		let group = [];
		conditioninfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                            </FormItem>),
                        colSpan:1
                    })
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		}); 
		return group
    }
    onOperatesClick(record,index,operate,flag){
        // console.log(record,index,operate,flag);
        const {actions} = this.props;
        if(flag=="3"){  //"客户联系"
           this.refs.customerContractModal.visible= true;
           actions.getRemindInfo({customerId:record.randomFieldId});
        }
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

Contact = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(Contact);

Contact = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(Contact);


function mapStateToProps(state) {
	const {contact,comsWeaTable} = state;
    return  {
        loading: contact.get('loading'),
        title: contact.get('title'),
        dataKey:contact.get('dataKey'),
        detailTabKey:contact.get('detailTabKey'),
        showSearchAd:contact.get('showSearchAd'),
        orderFields: contact.get('orderFields'),
        remindCount:contact.get('remindCount'),
        conditioninfo:contact.get('conditioninfo'),
        searchParamsAd:contact.get('searchParamsAd'),
        isClearNowPageStatus:contact.get('isClearNowPageStatus'),
        customerId:contact.get('customerId'),
        remindInfo:contact.get('remindInfo'),
         //table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...ContactAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Contact);
